package com.bitdf.txing.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.bitdf.txing.search.config.TxElasticConfig;
import com.bitdf.txing.search.constant.EsConstant;
import com.bitdf.txing.search.service.GroupSaveService;
import com.bitdf.txing.search.to.GroupInfoTo;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * @author Lizhiwei
 * @date 2023/1/26 2:03:56
 * 注释：
 */
@Service
public class GroupSaveServiceImpl implements GroupSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    RBloomFilter bloomFilter;

    /**
     * 保存组团数据到 es
     * @param groupInfoTo
     * @return
     * @throws IOException
     */
    @Override
    public boolean saveGroup(GroupInfoTo groupInfoTo) throws IOException {
        if (groupInfoTo.getPublishTime() == null) {
            groupInfoTo.setPublishTime(new Date());
        }
        groupInfoTo.setModifyFlag(0);

        IndexRequest indexRequest = new IndexRequest(EsConstant.GROUP_INDEX);
        indexRequest.id(groupInfoTo.getId().toString());
        String s = JSON.toJSONString(groupInfoTo);
        indexRequest.source(s, XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(indexRequest, TxElasticConfig.COMMON_OPTIONS);
        DocWriteResponse.Result result = response.getResult();
        if (result == DocWriteResponse.Result.CREATED) {
            // 加入到布隆过滤器
            bloomFilter.add(groupInfoTo.getId());
        }
        return true;
    }
}
